<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ style: { width: '78px' } }"
    :wrapper-col="{ style: { width: 'auto' } }"
    autocomplete="off"
    ref="refForm"
  >
    <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
      <a-input v-model:value="formState.name" placeholder="请输入名称" />
    </a-form-item>
    <a-form-item label="code" name="code" :rules="[{ required: true, message: '请输入code' }]">
      <a-input v-model:value="formState.code" placeholder="请输入code" />
    </a-form-item>
    <a-form-item
      label="资源类型"
      name="type"
      :rules="[{ required: true, message: '请选择资源类型' }]"
    >
      <a-select placeholder="请选择资源类型" v-model:value="formState.type" :options="typeList">
      </a-select>
    </a-form-item>
    <a-form-item
      label="资源说明"
      name="description"
      :rules="[{ required: true, message: '请输入资源说明' }]"
    >
      <a-textarea v-model:value="formState.description"></a-textarea>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { CreatePermissionDto } from '@/api/permission.api.ts'
import { type CreateDictDto, dictOptionsApi } from '@/api/dict.api.ts'

const formState = ref<CreatePermissionDto>({
  name: '',
  code: '',
  type: undefined,
  description: '',
})

const refForm = ref()
const submit = () => {
  return refForm.value.validateFields().then(() => {
    return formState.value
  })
}

const clearFormState = () => {
  getTypeList()
  return refForm.value.resetFields()
}

const setFormState = (record: CreatePermissionDto) => {
  formState.value = record
  getTypeList()
}

const typeList = ref<CreateDictDto['entries']>([])
const getTypeList = () => {
  dictOptionsApi('permission_options').then((res: CreateDictDto) => {
    typeList.value = res.entries
  })
}

defineExpose({
  submit,
  clearFormState,
  setFormState,
})

defineOptions({
  name: 'RoleEditForm',
})
</script>
